(function ($) {
    var page = "banner";
    layui.use(['element', 'form', 'layer', 'laytpl'], function () {
        var model = $(".banner-content");
        var layer = layui.layer;
        var form = layui.form;
        var laytpl = layui.laytpl;

        //是否有任务在执行
        var processing = false;

        var table = $(".banner-table").table({
            columns: [
                {
                    "name": "title",
                    "display": "标题"
                },
                {
                    "display": "链接地址",
                    "render": function (rowData) {
                        var url = rowData.url;
                        rowData.originUrl = url;
                        if (url) {
                            var equalIndex = url.indexOf("/headline.html?id=");
                            if (equalIndex > 0) {
                                rowData.url = url.substring(equalIndex + "/headline.html?id=".length);
                            }
                        }
                        //设置外链类型
                        if (/^\s*\d+\s*$/.test(rowData.url)) {
                            rowData.urlType = "01";
                        } else {
                            rowData.urlType = "02";
                        }
                        return rowData.url;
                    }
                },
                {
                    "display": "轮播图",
                    "render": function (rowData) {
                        return "<img class='banner-img' src='" + rowData.image + "'/>";
                    }
                },
                {
                    "name": "sort",
                    "display": "显示顺序"
                },
                {
                    "display": "轮播类型",
                    "render": function (rowData) {
                        if (rowData.type == "02") {
                            return "头条";
                        } else if (rowData.type == "03") {
                            return "对话";
                        } else if (rowData.type == "04") {
                            return "走势";
                        } else if (rowData.type == "05") {
                            return "前沿";
                        }
                        return "学院";
                    }
                },
                {
                    "display": "链接类型",
                    "render": function (rowData) {
                        if (rowData.urlType == "01") {
                            return "内链";
                        }
                        return "外链";
                    }
                },
                {
                    "display": "状态",
                    "render": function (rowData) {
                        if (rowData.status == "00") {
                            return "<span class='banner-offline'>禁用</span>";
                        }
                        return "<span class='banner-online'>启用</span>";
                    }
                },
                {
                    "display": "操作",
                    render: function (rowData) {
                        // return "<div class='opt-btn-group'><span class='edit-item'><i class=\"layui-icon\">&#xe642;</i>编辑</span>" +
                        //     "<span class='delete-item'><i class=\"layui-icon\">&#xe640;</i>删除</span>" +
                        //     "<span class='preview-item'><i class=\"layui-icon\">&#xe609;</i>预览</span>" +
                        //     "</div>";

                        var ret = "<div class='opt-btn-group'>";
                        if (rowData.status == "01") {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='red'>禁用</font></span>";
                        } else {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='#00bfff'>启用</font></span>";
                        }
                        ret += "<span class='edit-item'><i class=\"layui-icon\">&#xe642;</i>编辑</span>" +
                            /*"<span class='delete-item'><i class=\"layui-icon\">&#xe640;</i>删除</span>" +*/
                            //"<span class='preview-item'><i class=\"layui-icon\">&#xe609;</i>预览</span>" +
                            "</div>";

                        return ret;
                    }
                }
            ],
            url: "/hycj/banners",
            showTitle: false,
            formatData: function (data) {
                return data.datas;
            },
            pageSize: 1000
        });

        //编辑对话框
        model.on("click", ".edit-item", function (e) {
            var rowData = table.getRowData($(e.target).closest("tr"));
            laytpl($("#bannerForm").html()).render({
                model: "updateBannerForm",
                data: rowData
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "更新轮播",
                    content: content,
                    area: "600px",
                    maxHeight: app.clientHeight() - 50,
                    success: function () {
                        form.render("select");
                    }
                });
            });
        });

        //创建对话框
        model.on("click", ".create-item", function (e) {
            laytpl($("#bannerForm").html()).render({
                model: "addBannerForm",
                data: {}
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "创建轮播",
                    content: content,
                    area: "600px",
                    maxHeight: app.clientHeight() - 50,
                    success: function () {
                        form.render("select");
                    }
                });
            });
        });

        //删除对话框
        model.on("click", ".delete-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            layer.msg('您确认删除<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {
                    $.getJsonData("/hycj/banners"
                        , {id: selectedData.id}
                        , {type: "Delete"})
                        .done(function () {
                            layer.msg("删除完成");
                            table.refresh();
                        }).fail(function () {
                        layer.msg("删除失败, 请稍后重试!");
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //禁用/启用对话框
        model.on("click", ".update-status-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            var tipInfo = "禁用";
            //禁用改启用
            if (selectedData.status == "00") {
                tipInfo = "启用";
                selectedData.status = "01";
            } else {
                //启用改禁用
                selectedData.status = "00";
            }
            layer.msg('您确认' + tipInfo + '<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {

                    $.getJsonData("/hycj/banners", selectedData, {type: "Put"}).done(function (data) {
                        if (data.code != "200") {
                            layer.msg('操作失败', {icon: 2});
                        } else {
                            app.showSuccess();
                            table.refresh();
                        }
                        processing = false;
                    }).fail(function () {
                        processing = false;
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //预览
        model.on("click", ".preview-item", function (e) {
            var selectedData = table.getRowData($(e.target).closest("tr"));
            window.open(selectedData.originUrl);
        });

        //搜索
        form.on('submit(searchBannerForm)', function (data) {
            if (!data.form) {
                return false
            }
            table.refresh(data.field);
            return false;
        });

        //新增
        form.on('submit(addBannerForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;

            //头条连接拼接
            if (data.field.urlType === "01") {
                data.field.url = "http://h5.hooview.com/headline.html?id=" + data.field.url;
            }

            delete data.field.urlType;
            $.getJsonData("/hycj/banners", data.field, {type: "Post"}).done(function (data) {
                if (data.code != "200") {
                    layer.msg(data.message, {icon: 2});
                } else {
                    layer.msg('操作成功', {icon: 6});
                    layer.closeAll();
                    table.refresh();
                }

                processing = false;
            }).fail(function () {
                layer.msg("保存失败", {icon: 2});
                processing = false;
            });
            return false;
        });

        //更新
        form.on('submit(updateBannerForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            processing = true;

            //头条连接拼接
            if (data.field.urlType === "01") {
                data.field.url = "http://h5.hooview.com/headline.html?id=" + data.field.url;
            }
            delete data.field.urlType;
            $.getJsonData("/hycj/banners", data.field, {type: "Put"}).done(function (data) {
                app.showSuccess();
                table.refresh();
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        form.verify({
            integer: function (value, item) {
                if (value) {
                    try {
                        if (parseInt(value) != value) {
                            return "请输入整数";
                        }
                    } catch (error) {
                        return "请输入整数";
                    }
                }
            },
            positiveInteger: function (value, item) {//正整数
                if (value) {
                    try {
                        if (parseInt(value) != value || value <= 0) {
                            return "请输入正整数";
                        }
                    } catch (error) {
                        return "请输入正整数";
                    }
                }
            },
            bannerUrl: function (value, item) {
                //轮播连接
                var urlType = $("[name='urlType']").val();
                if (urlType == "01") {
                    if (!/\d+/.test(value)) {
                        return "链接类型为头条类型时，链接需为头条的ID";
                    }
                } else {
                    if (!/^(http:\/\/)|(https:\/\/).+$/i.test(value)) {
                        return "链接类型为外链类型时，链接需要为http或https协议";
                    }
                }
            }
        });

        app.bindPageEvents(page, function () {
            //上传轮播图
            $(document).on("click", ".banner-form .add-image", function (e) {
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        var uploadItem = uploadRet[0];
                        $addBtn.closest(".logo-img-container").html("<img src=\"" + uploadItem.path + "\" class=\"logo-item add-image\"/>");
                        $(".banner-form [name='image']").val(uploadItem.path);
                    }
                });
            });
        });
    });
})(jQuery);